<template>
  <a-range-picker
    :size="props.size"
    allowClear
    class="filed-wrapper"
    v-model:value="state.searchDate"
    :valueFormat="props.showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'"
    :ranges="props.showRanges ? ranges : undefined"
    :disabled-date="props.disabledDate"
    @change="searchDateChange"
    :show-time="props.showTime ? showTimeConfig : null"
    v-bind="props.minWidth ? { style: `min-width: ${props.minWidth}px` } : {}"
    :defaultPickerValue="state?.searchDate?.[0] != '' ? undefined : props.defaultPickerValue || undefined"
  />
</template>
<script lang="ts" setup>
import { useRanges } from '../../hooks/index';
import dayjs from 'dayjs';
import { reactive, watch } from 'vue';

const props = withDefaults(
  defineProps<{
    start: string | number; //开始时间
    end: string | number; //结束时间
    showTime?: boolean; //显示时刻
    showRanges?: boolean; //快捷操作
    disabledDate?: (current: dayjs.Dayjs) => boolean; //禁用日期回调
    minWidth?: number; // 最小宽度
    defaultPickerValue?: [dayjs.Dayjs, dayjs.Dayjs];
    size: 'large' | 'middle' | 'small';
  }>(),
  {
    size: 'middle',
  },
);

const emit = defineEmits<{
  (e: 'update:start', value: string): void;
  (e: 'update:end', value: string): void;
  (e: 'change', value: [string, string]): void;
}>();

const state = reactive<{
  searchDate: [string, string] | [dayjs.Dayjs, dayjs.Dayjs];
}>({
  searchDate: ['', ''],
});

const showTimeConfig = {
  hideDisabledOptions: true,
  defaultValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('11:59:59', 'HH:mm:ss')],
};

watch(
  props,
  () => {
    let start = props.start,
      end = props.end;
    if (parseInt(props.start as string) == props.start) start = dayjs(start).format('YYYY-MM-DD HH:mm:ss');
    if (parseInt(props.end as string) == props.end) end = dayjs(end).format('YYYY-MM-DD HH:mm:ss');
    state.searchDate = [(start as string) || '', (end as string) || ''];
  },
  { immediate: true },
);

const ranges = useRanges();

const searchDateChange = (values: [string, string] | [dayjs.Dayjs, dayjs.Dayjs]) => {
  if (!props.showTime) {
    if (values?.[0]) values[0] = dayjs(values?.[0]).format('YYYY-MM-DD 00:00:00');
    if (values?.[1]) values[1] = dayjs(values?.[1]).format('YYYY-MM-DD 23:59:59');
  }
  emit('update:start', (values?.[0] as string) || '');
  emit('update:end', (values?.[1] as string) || '');
  emit('change', (values as [string, string]) || ['', '']);
};
</script>
<style scoped>
/* .filed-wrapper{
  min-width: 240px;
} */
</style>
